#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# account_dialog.py 
#
#  Copyright (c) 2007 INdT (Instituto Nokia de Technologia)
#                2007 Kenneth Christiansen
#
#  Author: Kenneth Rohde Christiansen <kenneth.christiansen@gmail.com>
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 2 of the
#  License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA

import pygtk
pygtk.require("2.0")
import gtk
import gobject
import pango

import icon_theme
from account_forms import AccountFormFactory
from protocol_combo import ProtocolCombo

from gettext import gettext as _

class AccountDialog(gtk.Dialog):

    (
    ACCOUNT_LIST_ICON,
    ACCOUNT_LIST_ALIAS,
    ACCOUNT_LIST_PROTOCOL,
    ACCOUNT_LIST_EDITED,
    ACCOUNT_LIST_DATA
    ) = range(5)

    def __init__(self, parent=None):
        gtk.Dialog.__init__(self, title=_("Accounts - Ereséva"), parent=parent, \
            flags=gtk.DIALOG_DESTROY_WITH_PARENT,
            buttons=( gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE ))

        self.resize(440, 330)
        self.set_property("icon-name", 'ereseva')

        self.editing_now = None
        self.protocol_page = {}

        self.hbox = gtk.HBox(spacing=4)
        self.vbox.pack_start(self.hbox, True, True, 2)

        self.account_list_vbox = gtk.VBox(spacing=1)
        self.hbox.pack_start(self.account_list_vbox, False, True, 0)

        self.scrolled_account_list = gtk.ScrolledWindow(None, None)
        self.scrolled_account_list.set_size_request(180, -1)
        self.scrolled_account_list.set_border_width(3)
        self.scrolled_account_list.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        self.scrolled_account_list.set_shadow_type(gtk.SHADOW_ETCHED_IN)

        self.account_treeview = gtk.TreeView()
        self.account_treeview.connect('cursor-changed', self.on_account_selected)
        self._assemble_account_treeview()
        self.scrolled_account_list.add(self.account_treeview)

        self.buttonbox = gtk.HButtonBox()
        self.buttonbox.set_layout(gtk.BUTTONBOX_SPREAD)
        self.buttonbox.set_spacing(3)

        self.add_button = gtk.Button(stock="gtk-add")
        self.add_button.connect('clicked', self.on_add_button_clicked)
        self.buttonbox.add(self.add_button)

        self.remove_button = gtk.Button(stock="gtk-remove")
        self.remove_button.connect('clicked', self.on_remove_button_clicked)
        self.buttonbox.add(self.remove_button)

        self.account_list_vbox.pack_start(self.scrolled_account_list, True, True, 0)
        self.account_list_vbox.pack_start(self.buttonbox, False, True, 0)

        self.account_form_vbox = gtk.VBox(spacing=1)
        self.hbox.pack_start(self.account_form_vbox, True, True, 0)

        self.account_label = gtk.Label("<b>Account</b>")
        self.account_label.set_use_markup(True)
        self.account_label.set_alignment(0, 0.5)

        self.account_form_vbox.pack_start(self.account_label, False, True, 0)

        self.protocol_combo = ProtocolCombo()
        self.protocol_combo.set_active(0)
        self.protocol_combo_handler_id = \
                self.protocol_combo.connect('changed', \
                self.on_protocol_combo_changed)

        self.account_form_vbox.pack_start(self.protocol_combo, False, True, 0)

        self.forms_notebook = gtk.Notebook()
        self.forms_notebook.set_show_tabs(False)
        self.forms_notebook.set_show_border(False)
        self.account_form_vbox.pack_start(self.forms_notebook, True, True, 0)

        account_form_factory = AccountFormFactory()

        gtalk_form = account_form_factory.build_account_form('google-talk')
        gtalk_form.connect('value-changed', self.on_account_data_changed)
        self.protocol_page[ProtocolCombo.PROTOCOL_XMPP] = \
            self.forms_notebook.append_page(gtalk_form)

        msn_form = account_form_factory.build_account_form('msn-messenger')
        msn_form.connect('value-changed', self.on_account_data_changed)
        self.protocol_page[ProtocolCombo.PROTOCOL_MSN] = \
            self.forms_notebook.append_page(msn_form)

        self.account_form_vbox.set_sensitive(False)

        self.show_all()


    def set_account_data(self, protocol, account_id, password):
        page = self.protocol_page[protocol]
        self.forms_notebook.set_current_page(page)

        form = self.forms_notebook.get_nth_page(page)
        form.set_value('account', account_id)
        form.set_value('password', password)

        data = form.get_data()

        pixbuf = self.protocol_combo.get_protocol_icon(protocol)
        iter = self.account_store.append([pixbuf, account_id,
            ProtocolCombo.PROTOCOL_XMPP, True, data])

        path = self.account_store.get_path(iter)
        self.account_treeview.set_cursor(path)

        if len(self.account_store) == 1:
            self.account_form_vbox.set_sensitive(True)


    def on_account_selected(self, treeview):
        """To edit an account click it on the accounts' treeview."""

        path = treeview.get_cursor()[0]
        self.editing_now = self.account_store.get_iter(path)
        protocol = self.account_store.get_value(self.editing_now, \
                AccountDialog.ACCOUNT_LIST_PROTOCOL)
        account_data = self.account_store.get_value(self.editing_now, \
                AccountDialog.ACCOUNT_LIST_DATA)

        self.protocol_combo.disconnect(self.protocol_combo_handler_id)
        self.protocol_combo.set_selected_protocol(protocol)
        self.protocol_combo_handler_id = \
                self.protocol_combo.connect('changed', \
                self.on_protocol_combo_changed)

        page = self.protocol_page[protocol]
        self.forms_notebook.set_current_page(page)

        form = self.forms_notebook.get_nth_page(page)
        form.set_data(account_data)


    def on_account_data_changed(self, account_form, field_name):
        if not self.editing_now:
            return

        edited = self.account_store.get_value(self.editing_now, \
                self.ACCOUNT_LIST_EDITED)
        data = self.account_store.get_value(self.editing_now, \
                self.ACCOUNT_LIST_DATA)

        if data == None:
            return

        value = account_form.get_value(field_name)
        data[field_name] = value

        if field_name == 'account' and not edited:
            self.account_store.set(self.editing_now, \
                    AccountDialog.ACCOUNT_LIST_ALIAS, \
                    value)


    def on_protocol_combo_changed(self, combo):
        protocol = combo.get_selected_protocol()

        previous_page = self.forms_notebook.get_current_page()
        previous_form = self.forms_notebook.get_nth_page(previous_page)

        previous_form_data = previous_form.get_data()

        page = self.protocol_page[protocol]
        self.forms_notebook.set_current_page(page)

        form = self.forms_notebook.get_nth_page(page)
        form.reset_data()
        form.set_value('account', previous_form_data['account'])
        form.set_value('password', previous_form_data['password'])
        data = form.get_data()

        protocol_icon = combo.get_selected_protocol_icon()

        self.account_store.set(self.editing_now, \
                AccountDialog.ACCOUNT_LIST_ICON, protocol_icon, \
                AccountDialog.ACCOUNT_LIST_PROTOCOL, protocol, \
                AccountDialog.ACCOUNT_LIST_DATA, data)


    def on_add_button_clicked(self, button):
        pixbuf = self.protocol_combo.get_protocol_icon(ProtocolCombo.PROTOCOL_XMPP)
        protocol = ProtocolCombo.PROTOCOL_XMPP
        page = self.protocol_page[protocol]
        form = self.forms_notebook.get_nth_page(page)

        iter = self.account_store.append([pixbuf, '',
                ProtocolCombo.PROTOCOL_XMPP, False,
                None])
        self.editing_now = iter

        form.reset_data()
        data = form.get_data()
        self.account_store.set(self.editing_now, \
                AccountDialog.ACCOUNT_LIST_DATA, data)

        path = self.account_store.get_path(iter)
        self.account_treeview.set_cursor(path)

        if len(self.account_store) == 1:
            self.account_form_vbox.set_sensitive(True)


    def on_remove_button_clicked(self, button):
        path, tmp = self.account_treeview.get_cursor()
        if not path:
            return
        iter = self.account_store.get_iter(path)
        self.account_store.remove(iter)

        self.forms_notebook.set_current_page(0)

        if len(self.account_store) < 1 :
            self.account_form_vbox.set_sensitive(False)


    def _assemble_account_treeview(self):
        self.account_treeview.set_headers_visible(False)

        cell_pix = gtk.CellRendererPixbuf()
        cell_pix.set_fixed_size(22, -1)

        cell_text = gtk.CellRendererText()
        cell_text.set_property('editable', True)
        cell_text.set_property('ellipsize', pango.ELLIPSIZE_END)

        def do_on_text_edited (cell, path, new_text, user_data=None):
            self.account_store[path][AccountDialog.ACCOUNT_LIST_ALIAS] = new_text
            self.account_store[path][AccountDialog.ACCOUNT_LIST_EDITED] = True

        cell_text.connect('edited', do_on_text_edited)

        column = gtk.TreeViewColumn('', cell_pix, pixbuf=0)
        self.account_treeview.append_column(column)

        column = gtk.TreeViewColumn(_("Accounts"), cell_text, text=1)
        self.account_treeview.append_column(column)

        self.account_store = gtk.ListStore (gtk.gdk.Pixbuf, # Account image
            str,                  # Account text
            int,                  # Protocol identifier
            bool,                 # Edited
            gobject.TYPE_PYOBJECT # Account info
        )

        self.account_treeview.set_model(self.account_store)


if __name__ == "__main__":
    window = AccountDialog()
    window.connect('destroy', gtk.main_quit)
    gtk.main()

